//
//  ZCRegisterViewController.m
//  Unicom
//
//  Created by increase on 16/1/12.
//  Copyright © 2016年 increase. All rights reserved.
//
#define REDCOLOR [UIColor colorWithRed:1.0 green:0.0 blue:.0 alpha:1.0]

#import "ZCRegisterViewController.h"
#import <ifaddrs.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "AFNetworkHandler.h"
#import "ZCLoginViewController.h"

@interface ZCRegisterViewController ()<NSURLConnectionDelegate, NSURLConnectionDataDelegate>
{
    NSMutableData   *_serverData;
}
@property (nonatomic, strong) UITextField *textField;

@end

@implementation ZCRegisterViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (!([[[NSUserDefaults standardUserDefaults] objectForKey:@"url"] isEqualToString:@""] || [[NSUserDefaults standardUserDefaults] objectForKey:@"url"] == NULL)) {
        ZCLoginViewController *loginVC = [[ZCLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:NO];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"系统注册";
    [self createRegisterUI];
    
}

#pragma mark - 创建注册UI
- (void)createRegisterUI
{
    //公司
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 350, 30)];
    [self.view addSubview:titleLabel];
    titleLabel.textColor = REDCOLOR;
    titleLabel.text = @"出品公司：青岛英凯利信息科技有限公司";
    
    //产品
    UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(titleLabel.frame.origin.x, 45, 350, 30)];
    productLabel.textColor = REDCOLOR;
    productLabel.text = @"产品：联通OSS2.0";
    [self.view addSubview:productLabel];
    
    //版本
    UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 350, 30)];
    versionLabel.textColor = REDCOLOR;
    versionLabel.text = @"版本:V1";
    [self.view addSubview:versionLabel];
    
    //mac
    NSString *mac_str = [self getMacAddress];
    UILabel *macLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 115, 350, 30)];
    [self.view addSubview:macLabel];
    macLabel.textColor = REDCOLOR;
    macLabel.text = [NSString stringWithFormat:@"终端序列号:%@", mac_str];
    NSLog(@"Get MAC Address %@",mac_str); //B4:F0:AB:1C:05:93
    
    //注册码
    UILabel *codeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 150, 60, 30)];
    [self.view addSubview:codeLabel];
    codeLabel.text = @"注册码:";
    codeLabel.textColor = REDCOLOR;
    
    //textField
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(75, 150, 200, 30)];
    [self.view addSubview:self.textField];
    self.textField.borderStyle = UITextBorderStyleLine;
    
    //注册button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.backgroundColor = REDCOLOR;
    [button setTitle:@"注册" forState:0];
    [button addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(280, 150, 50, 30);
    [self.view addSubview:button];

}

#pragma mark - 获取mac地址
- (NSString *)getMacAddress
{
    int mib[6];
    size_t len;
    char *buf;
    unsigned char *ptr;
    struct if_msghdr *ifm;
    struct sockaddr_dl *sdl;
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}


#pragma mark - 注册跳转
- (void)registerAction
{
    NSLog(@"注册");
    

    NSString *macString = [self getMacAddress];
    NSString *codeString = self.textField.text;
    
    NSString *str2 = [NSString stringWithFormat:@"ck=a&&xmlstr=<?xml version=\"1.0\" encoding=\"UTF-8\"?><WEBSERVICESYNC><HEADER></HEADER><BODY><SERIALNO>11</SERIALNO><VERSION>V1.0</VERSION><USER>123</USER><PASSWORD>AC59075B964B0715</PASSWORD><CLIENTID>%@</CLIENTID><REGCODE>%@</REGCODE></BODY></WEBSERVICESYNC>", macString, codeString];
    
    NSLog(@"%@", str2);
 
//    [AFNetworkHandler submitData:@"http://5891.s30.javaidc.com/service/Reg" parameters:str2];
    
    

    NSString *urlString = @"http://5891.s30.javaidc.com/service/Reg";
    
    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setTimeoutInterval:5.0];

    [request setHTTPMethod:@"post"];

    NSData *body = [str2 dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:body];

    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    [conn start];
    
}

#pragma mark - 连接代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"开始接受服务器的返回请求%@", response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    _serverData = [NSMutableData data];
    [_serverData appendData:data];
    
    NSLog(@"中间接收的数据：%@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc]initWithData:_serverData encoding:NSUTF8StringEncoding];
    NSLog(@"connectionDidFinishLoading解码后的字符串是：%@", string);
    
    NSArray *array = [string componentsSeparatedByString:@"<SERVERADDRESS>"];
    NSString *newStr2 = array.lastObject;
    NSArray *arry2 = [newStr2 componentsSeparatedByString:@"<"];
    
    NSUserDefaults *url = [NSUserDefaults standardUserDefaults];
    [url setObject: [NSString stringWithFormat:@"%@", arry2.firstObject] forKey:@"url"];
    NSLog(@"~~~~~~%@", [url objectForKey:@"url"]);
    
    ZCLoginViewController *loginVC = [[ZCLoginViewController alloc] init];
    
    if ([[url objectForKey:@"url"] isEqualToString:@""]) {
        NSLog(@"注册失败");
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"注册失败,请重新输入注册码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        [self.navigationController pushViewController:loginVC animated:YES];
    }

    
}

// 网络请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"失败 %@", error.localizedDescription);
    
    _serverData = nil;
}

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
    NSLog(@"2222222：");
    NSLog(@"发送数据 %ld %ld %ld", (long)bytesWritten, (long)totalBytesWritten, (long)totalBytesExpectedToWrite);
}
//




#pragma mark - 键盘回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
